package indi.qing.interceptor;


import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import indi.qing.common.JWTUtils;
import indi.qing.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Result result = new Result();
        // http连接时，客户端应该是在头信息中携带令牌
        String token = request.getHeader("token");
        log.info("http");
        if(StringUtils.isBlank(token)) {
            // websocket连接时，令牌放在url参数上，以后重构
            token = request.getParameter("token");
            log.info("ws");
        }
        try {
            JWTUtils.verify(token);
            log.info("ok");
            return true;
        } catch (SignatureVerificationException e){
            e.printStackTrace();
            result.setMsg("无效签名");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            result.setMsg("token过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            result.setMsg("token算法不匹配");
        }catch (NullPointerException e){
            e.printStackTrace();
            result.setMsg("token为空");
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("token无效");
        }
        result.setCode(401);
        String json = JSON.toJSONString(result);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
